<template>
  <div class="panel">
    <div class="section">
      <treeselect class="treeselect-main" placeholder="请选择方案类型" v-model="value" :multiple="false" :options="treeData"
        @input="input" />
      <div class="table-box">
        <el-table ref="table" :data="tableData" style="width: 100%" :border="true">
          <el-table-column prop="name" label="名称"> </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button @click="handleClick(scope.row)" type="text" size="small">
                打开
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
  </div>
</template>

<script>
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import schemeApi from "@/api/Scheme";
import { mapMutations, mapState } from "vuex";
import { uuid } from "@/utils/tools";
import PlotManager from "@/utils/drawHelper/plotManager";
import {
  drawPoint,
  drawPolygon,
  drawLine,
  drawRact,
  drawCircle,
  drawModels
} from "@/utils/drawEntitiy";

export default {
  components: {
    Treeselect,
  },
  data() {
    return {
      value: null,
      treeData: [],
      tableData: [],
    };
  },
  computed: {
    ...mapState("layer", ["layerIds", "objectIds"]),
  },
  mounted() {
    this.getTreeData();
  },
  methods: {
    ...mapMutations("layer", ["addObjectId", "addLayerId"]),
    // 方案类型
    getTreeData() {
      let param = {};
      schemeApi.typeTree(param).then((res) => {
        if (res.status === 200) {
          this.treeData = res.data.data;
          this.getJson(this.treeData);
        }
      });
    },
    getJson(data) {
      for (let item of data) {
        if (!item.children || !item.children.length) {
          delete item.children;
        } else {
          this.getJson(item.children);
        }
      }
    },
    // 方案数据
    getList(typeId) {
      schemeApi.query({ typeId }).then((res) => {
        if (res.status === 200) {
          this.tableData = res.data.data;
        }
      });
    },
    input(value) {
      this.getList(value);
    },
    // 加载方案库数据
    handleClick(param) {
      earth.objectsManager.removeAll();
      earth.layersManager.removeAll();
      let data = JSON.parse(param.dataText);
      if (data.type == "scheme") {
        let { objectList, layerList } = data.datas;
        this.loadModules(objectList);
        this.loadLayers(layerList);
      }
    },
    // 影像图层
    loadLayers(infos) {
      let layerIds = earth.layersManager.layerList.map((e) => e.id);
      infos.map((layer) => {
        if (!layerIds.includes(layer.id)) {
          earth.layersManager.loadServerTypeMap(
            layer.id,
            layer.name,
            layer.info
          );
          this.addLayerId(layer.id);
        }
      });
    },
    // 数据图层
    loadModules(schemeList) {
      let { objectsManager, core, effects } = earth;
      schemeList.map((scheme) => {
        switch (scheme.info.type) {
          case objectsManager.modelTypes.tracker:
            this.showDrawHelper(scheme);
            break;
          case objectsManager.modelTypes.entities:
            this.showEntities(scheme);
            break;
          case objectsManager.modelTypes.model:
            let target = new core.Entities(viewer)
            let ret = objectsManager.cacheObjectLayer(scheme.id, scheme.name, target, scheme.info);
            let _entities = drawModels(scheme.info.featureCollection);
            ret.value.addEntities(_entities);
            this.addObjectId(ret.id);
            break;
          case effects.types.videoShed:
            this.drawShed(scheme.info);
            break;
          default:
            objectsManager
              .loadObjectsTypeMap(scheme.id, scheme.name, scheme.info)
              .then((ret) => {
                if (ret.type === objectsManager.ef.types.terrainClipPlan) {
                  viewer.scene.globe.depthTestAgainstTerrain = true;
                  ret.value.draw(scheme.info.positions);
                }
                if (scheme.info.type == objectsManager.modelTypes.bim) {
                  // 3dtileset 调整位置
                  this.updatePosition(ret, scheme.info);
                }
                this.addObjectId(ret.id);
              })
              .catch((error) => {
                this.$message(error);
              });
            break;
        }
      });
    },

    // 3dtileset 调整位置
    updatePosition(ret, info) {
      let tilesetLoader = ret.value;
      if (info.longitude != 0 && info.longitude != 0) {
        let cartesian3 = Cesium.Cartesian3.fromDegrees(Number(info.longitude), Number(info.latitude), Number(info.height));
        tilesetLoader.position = cartesian3;
      }

      tilesetLoader.rotation = {
        x: info.rotateX,
        y: info.rotateY,
        z: info.rotateZ
      };

      tilesetLoader.translation = {
        x: info.offsetX,
        y: info.offsetY,
        z: info.offsetZ
      };
      // viewer.flyTo(ret.value.tileset);
    },

    drawShed(param) {
      let me = this;
      let { objectsManager } = window.earth;

      function createVideoEle(url, vid = "visualDomId") {
        let videos = document.getElementById("videos")
        if (!videos) {
          let root = document.getElementById("app")
          videos = document.createElement("div");
          videos.setAttribute("id", "videos");
          videos.className = 'videos';
          root.appendChild(videos);
        }
        var v = document.createElement("video");
        v.setAttribute("id", vid);
        v.setAttribute("width", "400px");
        v.setAttribute("src", url);
        v.setAttribute("controls", !0);
        v.setAttribute("autoplay", !0);
        v.setAttribute("playsInline", !0);
        v.setAttribute("webkit-playsinline", !0);
        videos.appendChild(v);
      }

      if (param.options.live) {
        createVideoEle(param.options.url, param.id);
        var player = new EZUIKit.EZUIPlayer(param.id);
      }

      objectsManager.loadObjectsTypeMap(param.id, param.schemeName, param).then(ret => {
        ret.value.draw(param.options);
        me.addObjectId(ret.id);
      }).catch(error => {
        console.log('videoShed: ', error)
      });
    },


    showEntities(scheme) {
      let me = this;
      let { objectsManager } = earth;
      let features = scheme.info.featureCollection.features;
      objectsManager.loadObjectsTypeMap(scheme.id, scheme.name, scheme.info).then(ret => {
        let _entities = features.map(feature => {
          switch (feature.geometry.type) {
            case "Point":
              return drawPoint(feature);
            case "LineString":
              return drawLine(feature);
            case "Polygon":
              return drawPolygon(feature);
            case "Rectangle":
              return drawRact(feature);
            case "Circle":
              return drawCircle(feature);
            default:
              break;
          }
        })
        ret.value.addEntities(_entities);
        me.addObjectId(ret.id);
      }).catch(error => {
        notification.warning({ message: error });
      });
    },
    // 加载标绘数据
    showDrawHelper(scheme) {
      let { objectsManager } = earth;
      let tracker = new PlotManager(viewer, uuid(16));

      let color = scheme.info.hasOwnProperty("fullColor")
        ? scheme.info.fullColor
        : "#ffff00";
      plotting.fullColor =
        Cesium.Color.fromCssColorString(color).withAlpha(0.5);
      tracker.showShapeDic(scheme.info.data);
      let params = {
        type: objectsManager.modelTypes.tracker,
        data: scheme.info.data,
      };
      let ret = objectsManager.cacheObjectLayer(
        tracker._layerId,
        scheme.name,
        tracker,
        params
      );
      this.addObjectId(ret.id);
    },
  },
};
</script>

<style scoped lang="scss">
.panel {
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  color: #666;
  overflow-y: auto;
}

.section {
  padding: 5px;
}

:deep.el-table .cell {
  white-space: nowrap !important;
}
</style>